import { DbConfig } from "../../config/DbConfig";
import { MysqlClient } from "./MySqlClient";
import fs = require("fs")
import path = require("path")
import { Logger } from "./Logger";

export class MysqlManager {

    // 导出结构不导出数据
    //  /usr/local/mysql/bin/mysqldump --opt -d test -u root -p > ~/test.sql 

    // 导出数据不导出结构
    // mysqldump　-t　数据库名　-uroot　-p　>　xxx.sql

    // 导出数据和表结构
    // mysqldump　数据库名　-uroot　-p　>　xxx.sql

    // 导出特定表的结构
    // mysqldump　-uroot　-p　-B　数据库名　--table　表名　>　xxx.sql

    public static instance: MysqlManager = new MysqlManager();

    private dbMap: Map<string, MysqlClient> = new Map<string, MysqlClient>();

    public async createClient(dbName: string, dbType: number) {
        let realDbName: string = this.getCodeDbName(dbName, dbType)
        let dbConfig: DbConfig = DbConfig.getDbConfig(dbType)
        let client: MysqlClient = await MysqlClient.create(dbName, dbConfig.host, dbConfig.port, dbConfig.user, dbConfig.pass);
        this.dbMap.set(realDbName, client);
        return client;
    }

    private getCodeDbName(dbName: string, dbType: number) {
        let realDbName: string = dbName + "_db" + dbType
        return realDbName;
    }


    public async getDb(dbName: string, dbType: number = DbConfig.now_db_type) {
        let db: MysqlClient;
        let realDbName: string = this.getCodeDbName(dbName, dbType)
        if (this.dbMap.has(realDbName)) {
            db = this.dbMap.get(realDbName);
        } else {
            Logger.info("数据库client", dbName);
            db = await this.createClient(dbName, dbType);
        }
        return db;
    }
}